import axios from 'axios'
import { THREE } from 'threebox-plugin'
import Constants from './constants'
import util from './util'

class FloorManager {
  constructor(vueInstance) {
    this.map = vueInstance.map
    this.tb = vueInstance.threeBoxLayer.tb
    this.threeBoxLayer = vueInstance.threeBoxLayer
    this.vueInstance = vueInstance
    this.floorObjects = []
  }

  addFloors () {
    this.removeFloors()
    let {buildingId} = this.vueInstance.$store.state.buildingOverview
    // 创建group用来保存添加的楼层
    this.addedFloorGroup = []
    axios.get('./models/innerFloor.json').then(res => {
      const modelsList = res.data
      modelsList.forEach(ele => {
        // 排除未选中的楼层
        if(!ele.name.includes(buildingId)){
          return
        }
        const options = {
          type: 'gltf',
          obj: `./models/江湾雅园/inner/${ele.name}.glb`,
          scale: 1,
          units: 'meters',
          rotation: { x: 0, y: 0, z: 180 }, // default rotation
          anchor: 'auto',
          bbox: false,
          floor: ele.floor,
          repeat: ele.repeat,
          modelType: ele.modelType,
          tooltip: false,
          raycasted: false
        }
        this.tb.loadObj(options, (model) => {
          const { floor, repeat } = model.userData
          if (model.userData.repeat) {
            // 添加复制模型
            for (let i = floor, j = 0; j <= repeat; i++, j++) {
              const cloneModel = model.duplicate()
              cloneModel.setCoords([Constants.origin[0], Constants.origin[1], (i - floor) * 3.0])
              cloneModel.userData.floor = i
              cloneModel.name = `${buildingId}-${i}层`
              this.tb.add(cloneModel)
              this.floorObjects.push(cloneModel)
            }
            return
          }
          model.setCoords(Constants.origin)
          this.tb.add(model)
        })
      })
    })
  }

  removeFloors() {
    this.floorObjects.forEach(item => {
      this.tb.remove(item)
    })
    this.floorObjects = []
  }

  easeOut(floor) {
    if (this.isAnimate) {
      return
    }
    let { bearing } = this.vueInstance.$store.state.buildingOverview
    let floorObject = this.floorObjects.find(item => item.userData.floor == floor)
    if (!floorObject) {
      return
    }
    this.threeBoxLayer.floorPopAnimate(floorObject, -Constants.animateVec, -bearing)
    //this.threeBoxLayer.adjustFreeCamera(floorObject)
  }

  easeIn(floor) {
    if (this.isAnimate) {
      return
    }
    let { bearing } = this.vueInstance.$store.state.buildingOverview
    let floorObject = this.floorObjects.find(item => item.userData.floor == floor)
    if (!floorObject) {
      return
    }
    this.threeBoxLayer.floorPopAnimate(floorObject, Constants.animateVec, -bearing)
  }
}

export default FloorManager